package org.railage.server.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.railage.server.HibernateUtil;
import org.railage.server.entities.Station;

public class StationDAOImpl implements StationDAO {

	private static final Logger log = Logger.getLogger(StationDAOImpl.class);

	public int addStation(String stationName) {
		Session session = null;
		Transaction transaction = null;
		int result = -1;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			Query query = session
					.createSQLQuery("select fn_add_station(:stationName)");
			query.setString("stationName", stationName);
			result = (Integer) query.uniqueResult();
			transaction.commit();
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return result;
	}

	public int deleteStation(String stationName) {
		Session session = null;
		Transaction transaction = null;
		int result = -1;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			Query query = session
					.createSQLQuery("select fn_delete_station(:stationName)");
			query.setString("stationName", stationName);
			result = (Integer) query.uniqueResult();
			transaction.commit();
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<Station> getAllStations() {
		Session session = null;
		List<Station> stations = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			stations = (List<Station>) session.createCriteria(Station.class)
					.list();
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return stations;
	}

	@SuppressWarnings("unchecked")
	public List<Station> getOrderedStationsOfTrip(int tripID) {
		Session session = null;
		List<Station> stations = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			Query query = session.getNamedQuery("getOrderedStationsOfTrip");
			query.setInteger("id_trip", tripID);
			stations = (List<Station>) query.list();
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return stations;
	}

}
